<script setup lang="ts">
import type { FormInstance, CascaderProps } from 'element-plus';
import { ElMessage } from "element-plus";
import { usePostStore } from '@/store/post';
import axios from "axios";

const store = usePostStore();

const formRef = ref()

const form = reactive({
  modelPath: [
    // "studio/algo/",
    // "studio/algo/1/",
    // "studio/algo/1/data.json"
  ],
  resultPath: [
    // "studio/operator/",
    // "studio/operator/add/",
    // "studio/operator/add/add_e33b0130dea80b0bed3b5447b2e8d060.zip"
  ]
})
const rules = reactive({
  modelPath: [{required: true, message: '请选择输入文件'}],
  resultPath: [{required: true, message: '请选择输出文件'}],
})

type OssFile = {
  directory: boolean;
  key: string;
  name: string;
}
const props: CascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { value='studio/' } = node
    // console.log('--- node: ', node.value)
    axios.get(`/oss_file?directory=${value}`)
      .then(({ data }) => {
        // console.log('--- res: ', data)
        if (data.success) {
          const nodes = data.data.map(({directory, key, name}: OssFile) => ({label: name, value: key, leaf: !directory}));
          resolve(nodes)
        }
      })
      .catch((error) => {
        // console.log('--- err: ', err)
        ElMessage.error(error.message)
      })
  },
}

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      const modelPath = form.modelPath.slice(-1)[0]
      const resultPath = form.resultPath.slice(-1)[0]
      store.importModel({modelPath, resultPath});
    } else {
      console.log('error submit!', fields)
    }
  })
}

</script>

<template>
  <el-card header="模型导入" shadow="never" class="card">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-form-item label="输入文件" prop="modelPath">
        <el-cascader v-model="form.modelPath" :props="props" placeholder="选择文件" />
      </el-form-item>
      <el-form-item label="输出文件" prop="resultPath">
        <el-cascader v-model="form.resultPath" :props="props" placeholder="选择文件" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(formRef)">导入</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped lang="scss">
.row {
  &-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }
}
.card {
  flex: 0 0 auto;
  :deep(.el-form-item) {
    display: block;
  }
  :deep(.el-cascader) {
    width: 100%;
  }
  :deep(.el-input-group__append) {
    width: 4em;
    padding-right: 0;
    padding-left: 0;
  }
}
</style>